package com.imist.nettybasic4.server;

import com.imist.nettybasic4.codec.PacketCodecHandler;
import com.imist.nettybasic4.codec.PacketDecoder;
import com.imist.nettybasic4.codec.PacketEncoder;
import com.imist.nettybasic4.codec.Spliter;
import com.imist.nettybasic4.handler.IMIdleStateHandler;
import com.imist.nettybasic4.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.Date;


public class NettyServer {
    private static final int PORT = 8002;

    public static void main(String[] args) {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    //在 initChannel() 方法里面端添加一个逻辑处理器，这个处理器的作用就是负责数据的逻辑处理
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //调用 addLast() 方法 添加一个逻辑处理器，这个逻辑处理器为的就是在客户端建立连接成功之后，向服务端写数据
                            //ch.pipeline().addLast(new LifeCycleTextHandler());

                            ch.pipeline().addLast(new IMIdleStateHandler());
                            ch.pipeline().addLast(new Spliter());
                            // 统一编码解码器
                            ch.pipeline().addLast(PacketCodecHandler.INSTANCE);
                            //ch.pipeline().addLast(new PacketDecoder());

                            ch.pipeline().addLast(LoginRequestHandler.INSTANCE);

                            ch.pipeline().addLast(HeartbeatRequestHandler.INSTANCE);
                            //这里必须放在登录逻辑之后，不然登录逻辑是不会执行的（因为没有登录就直接关闭了连接）
                            ch.pipeline().addLast(AuthHandler.INSTANCE);
                            //同一种类型的handler并行处理，减少事件传播的路径
                            ch.pipeline().addLast(IMHandler.INSTANCE);

                        /*ch.pipeline().addLast(MessageRequestHandler.INSTANCE);
                        ch.pipeline().addLast(CreateGroupRequestHandler.INSTANCE);
                        ch.pipeline().addLast(JoinGroupRequestHandler.INSTANCE);
                        ch.pipeline().addLast(QuitGroupRequestHandler.INSTANCE);
                        ch.pipeline().addLast(ListGroupMemberRequestHandler.INSTANCE);
                        ch.pipeline().addLast(GroupMessageRequestHandler.INSTANCE);
                        ch.pipeline().addLast(LogoutRequestHandler.INSTANCE);*/

                            //ch.pipeline().addLast(new PacketEncoder());
                        }
                    });
            bind(serverBootstrap,PORT);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }

    private static void bind (ServerBootstrap bootstrap ,int port) throws InterruptedException {
        ChannelFuture channelFuture = bootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()){
                System.out.println(new Date()+" : 端口["+port+"]"+"绑定成功");
            }else {
                System.out.println(new Date()+" : 端口["+port+"]"+"绑定失败");
            }
        }).sync();
        //等待服务器socket关闭；
        channelFuture.channel().closeFuture().sync();

    }
}

